package com.eimf.saf.base.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author eden
 * @date 2013-11-18 下午3:09:45
 * @Description: TODO(这里用一句话描述这个类的作用)
 */
public class GenericsUtils
{
    public static Class<?> getGenericClass(final Class<?> clazz)
    {
        return GenericsUtils.getGenericClass(clazz, 0);
    }

    public static Class<?> getGenericClass(Class<?> clazz, final int index) throws IndexOutOfBoundsException
    {
        Type genType = clazz.getGenericSuperclass();
        while (!(genType instanceof ParameterizedType))
        {
            if (clazz == Object.class)
            {
                return Object.class;
            }
            clazz = clazz.getSuperclass();
            genType = clazz.getGenericSuperclass();
        }
        final Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if (index >= params.length || index < 0)
        {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size of Parameterized Type: " + params.length);
        }
        return (Class<?>) params[index];
    }
}
